﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Web.UI.HtmlControls;
using Yipusoft.SecurityEvaluate;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using System.Data;
using Yipusoft.Vehicle.BLL;
using Yipusoft.Vehicle.Model;
using Yipusoft.BasicBase.BLL;
using System.IO;
using System.Text;


public partial class Police_SecurityEvaluate_ParkCaption : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            init();

        }

    }

    void init()
    {
        List<SignContent> packLogs = new List<SignContent>();
        ViewState["packLogs"] = packLogs;
        BindDate();

        string DepartmentId = "";
        if (Request["DepartmentId"] != null)
        {
            DepartmentId = Request["DepartmentId"];
            ddlYear.SelectedValue = Request["year"];
            ddlWeek.SelectedValue = Request["week"];
        }
        else
        {
            DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        }
        BindData(DepartmentId);
    }
    void SetCaptionButton()
    {
        int week = GetWeekOfYear(DateTime.Now);
        if (week == (Convert.ToInt32(ddlWeek.SelectedValue) + 1))
        {
            btnCaption.Visible = true;
        }
        else
        {
            btnCaption.Visible = false;
        }
    }

    void BindDate()
    {
        for (int i = 2009; i <= 2050; i++)
        {
            ddlYear.Items.Add(new ListItem(i.ToString() + "年", i.ToString()));

        }
        ddlYear.SelectedValue = DateTime.Now.Year.ToString();
        BindWeek();
        BindWeekView();
    }

    void BindWeek()
    {
        int year = Convert.ToInt32(ddlYear.SelectedValue);
        for (int i = 1; i < GetWeekAmount(year); i++)
        {
            ddlWeek.Items.Add(new ListItem("第" + i + "周", i.ToString()));
        }
        ddlWeek.SelectedValue = (GetWeekOfYear(DateTime.Now) - 1).ToString();
    }

    /// <summary>
    /// 当前为该年中的第几周
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    int GetWeekOfYear(DateTime dt)
    {
        GregorianCalendar gc = new GregorianCalendar();
        return gc.GetWeekOfYear(dt, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
    }
    /// <summary>
    /// 获取某年中有多少周
    /// </summary>
    /// <param name="year">年</param>
    /// <returns></returns>
    int GetWeekAmount(int year)
    {
        DateTime end = new DateTime(year, 12, 31);
        System.Globalization.GregorianCalendar gc = new GregorianCalendar();
        return gc.GetWeekOfYear(end, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
    }
    protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindWeek();
        BindWeekView();
        //梆定数据
        string DepartmentId = "";
        if (Request["DepartmentId"] != null)
        {
            DepartmentId = Request["DepartmentId"];
        }
        else
        {
            DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        }
        BindData(DepartmentId);
    }

    string GetWeekOfStartAndEnd(int year, int week)
    {

        DateTime YearOfOne = new DateTime(year, 1, 1);
        int dayofWeek = Convert.ToInt32(YearOfOne.DayOfWeek);
        if (dayofWeek == 0)
        {
            dayofWeek = 7;
        }
        DateTime StartDate = YearOfOne.AddDays((week - 1) * 7).AddDays(-dayofWeek + 1);
        DateTime EndDate = StartDate.AddDays(6);
        return StartDate.ToString("MM月dd日") + "--" + EndDate.ToString("MM月dd日");
    }
    protected void ddlWeek_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindWeekView();

        string DepartmentId = "";
        if (Request["DepartmentId"] != null)
        {
            DepartmentId = Request["DepartmentId"];
        }
        else
        {
            DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        }
        BindData(DepartmentId);
    }

    void BindWeekView()
    {
        string DepartmentId = "";
        if (Request["DepartmentId"] != null)
        {
            DepartmentId = Request["DepartmentId"];
        }
        else
        {
            DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        }
        string AliasName = Yipusoft.Account.BLL.Department.GetDepartment(DepartmentId).AliasName;
        int year = Convert.ToInt32(ddlYear.SelectedValue);
        int week = Convert.ToInt32(ddlWeek.SelectedValue);
        lbldate.Text = AliasName + "支队(" + GetWeekOfStartAndEnd(year, week) + "）车场日登记";
    }

    void BindData(string DepartmentId)
    {
        List<SignContent> packLogs = ViewState["packLogs"] as List<SignContent>;

        //开始时间和结束时间
        int year = Convert.ToInt32(ddlYear.SelectedValue);
        int week = Convert.ToInt32(ddlWeek.SelectedValue);
        DateTime YearOfOne = new DateTime(year, 1, 1);
        int dayofWeek = Convert.ToInt32(YearOfOne.DayOfWeek);
        if (dayofWeek == 0)
        {
            dayofWeek = 7;
        }
        DateTime StartTime = YearOfOne.AddDays((week - 1) * 7).AddDays(-dayofWeek + 1);
        DateTime EndTime = StartTime.AddDays(7);

	

        //部门ID
        DepartmentId = DepartmentId.Substring(0, 4) + "000";
        int Week = Convert.ToInt32(ddlWeek.SelectedValue);
        //头
        HtmlTableRow tr = new HtmlTableRow();
        HtmlTableCell td = new HtmlTableCell();
        td.InnerText = "单位";
        td.Attributes.Add("style", "border-color:#888888;border-collapse:  collapse; padding: 10px; white-space:nowrap;  border-width: 1px; border-style:solid;text-align: left;");
        tr.Cells.Add(td);

        td = new HtmlTableCell();
        td.InnerText = "车辆";
        td.Attributes.Add("style", "border-color:#888888;border-collapse:  collapse; padding: 10px; white-space:nowrap;  border-width: 1px; border-style:solid;text-align: left;");
        tr.Cells.Add(td);

        td = new HtmlTableCell();
        td.Attributes.Add("style", "border-color:#888888;border-collapse:  collapse; padding: 10px; white-space:nowrap;  border-width: 1px; border-style:solid;text-align: left;");
        td.InnerText = "车辆情况";
        tr.Cells.Add(td);
        table.Rows.Add(tr);

        ParkLogDataContext pdc = new ParkLogDataContext();
        PackLogSign logSign = pdc.PackLogSign.Where(o => o.DepartmentId == DepartmentId && o.WeekCout == Week).FirstOrDefault();
	//Response.Write(logSign.Id.ToString() );
        //中间部分
        if (logSign != null)
        {//已存在

            tr = new HtmlTableRow();
            HtmlTableCell Departtd = new HtmlTableCell();

            List<PackSignContent> packSignContents = pdc.PackSignContent.Where(o => o.Sid == logSign.Id).ToList<PackSignContent>();
            if (packSignContents.Count == 0)
            {
                table.Rows.Clear();
                HtmlTableRow row = new HtmlTableRow();
                td = new HtmlTableCell();
                td.InnerText = "车辆一切正常！";
                row.Cells.Add(td);
                table.Rows.Add(row);
            }
            else
            {
                var pp = from o in packSignContents group o by o.DepartmentId into g select g.Key;
                List<string> DepartmentIds = pp.ToList<string>();
                foreach (string did in DepartmentIds)
                {
                    tr = new HtmlTableRow();
                    Departtd = new HtmlTableCell();
                    Departtd.InnerText = Department.GetDepartment(did).ShortName;
                    Departtd.Attributes.Add("style", "border-color:#888888;border-collapse:  collapse;padding: 10px; white-space:nowrap;  border-width: 1px; border-style:solid;text-align:left;");
                    tr.Cells.Add(Departtd);
                    List<PackSignContent> list = packSignContents.Where(o => o.DepartmentId == did).ToList();
                    for (int j = 0; j < list.Count; j++)
                    {
                        if (j > 0)
                        {
                            tr = new HtmlTableRow();
                        }
                        PackSignContent content = list[j];
                        td = new HtmlTableCell();
                        VehicleInfo vehicle = Vehicle.GetDetail(content.Vid);
                        if (vehicle != null)
                        {
                            td.InnerText = vehicle.VehicleName + "(" + vehicle.NumberPlate + ")";
                        }
                        else
                        {
                            td.InnerText = "此车辆已删除！";
                        }

                        td.Attributes.Add("style", "border-color:#888888;border-collapse:  collapse;padding: 10px; white-space:nowrap;  border-width: 1px; border-style:solid;text-align: left;");
                        tr.Cells.Add(td);

                        td = new HtmlTableCell();
                        td.Attributes.Add("style", "border-color:#888888;border-collapse:  collapse;padding: 10px;  border-width: 1px; border-style:solid;text-align: left;");
                        td.InnerHtml = content.Remark;
                        tr.Cells.Add(td);

                        table.Rows.Add(tr);
                    }

                    Departtd.RowSpan = list.Count;
                }

            }

            lblCaption.Text = logSign.Caption;
            lblCaption0.Text = logSign.Caption0;
            btnCaption.Visible = false;

            #region 是否签字
            //caption
            int NowWeek = GetWeekOfYear(DateTime.Now);
            //是否是签字时间
            if (NowWeek == (Convert.ToInt32(ddlWeek.SelectedValue) + 1) || DepartmentId.Substring(0, 4) == "1310")
            {
                //是否签字
                //值班首长
                if (logSign.Caption0 == null || logSign.Caption0 == "")
                {
                    //未签字
                    btnCaption0.Visible = true;
                }
                else
                {
                    btnCaption0.Visible = false;
                }
                //参谋长
                if (logSign.Caption == null || logSign.Caption == "")
                {
                    //未签字
                    btnCaption.Visible = true;
                }
                else
                {
                    btnCaption.Visible = false;
                }
            }
            else
            {
                btnCaption.Visible = false;
                btnCaption0.Visible = false;
            }
            #endregion

            if (logSign.Caption == null || logSign.Caption0 == null)
            {
                btnPrint.Visible = false;
            }
            else
            {
                btnPrint.Visible = true;
            }
        }
        else
        {//未存在

            //有问题车辆的部门
            List<string> DepartmentIds = Park.GetDamageDepartmentId(DepartmentId, StartTime, EndTime);
            if (DepartmentIds.Count == 0)
            {
                table.Rows.Clear();
                HtmlTableRow row = new HtmlTableRow();
                td = new HtmlTableCell();
                //是否是上一周的
                //int NowWeek1 = GetWeekOfYear(DateTime.Now);
                //if (NowWeek1 == (Convert.ToInt32(ddlWeek.SelectedValue) + 1))
                //{
                //    td.InnerText = "车辆一切正常！";
                //}
                //else
                //{
                //    td.InnerText = "没有数据！";
                //}

                td.InnerText = "车辆一切正常！";


                row.Cells.Add(td);
                table.Rows.Add(row);

            }
            for (int i = 0; i < DepartmentIds.Count; i++)
            {
                tr = new HtmlTableRow();
                HtmlTableCell Departtd = new HtmlTableCell();
                Departtd.InnerText = Department.GetDepartment(DepartmentIds[i]).ShortName;
                Departtd.Attributes.Add("style", "border-color:#888888;border-collapse:  collapse; white-space:nowrap;  border-width: 1px; border-style:solid;text-align:left;");
                tr.Cells.Add(Departtd);
                List<PackLogInfo> logs = getPackLogInfos(DepartmentIds[i], StartTime, EndTime);

                for (int j = 0; j < logs.Count; j++)
                {
                    if (j > 0)
                    {
                        tr = new HtmlTableRow();
                    }
                    PackLogInfo info = logs[j];
                    HtmlTableCell VehicleTd = new HtmlTableCell();
                    VehicleInfo vehicle = Vehicle.GetDetail(info.CarId);
                    if (vehicle != null)
                    {
                        VehicleTd.InnerText = vehicle.VehicleName + "(" + vehicle.NumberPlate + ")";
                    }
                    else
                    {
                        VehicleTd.InnerText = "";
                    }

                    VehicleTd.Attributes.Add("style", "border-color:#888888;border-collapse:  collapse; white-space:nowrap;  border-width: 1px; border-style:solid;text-align: left;");
                    tr.Cells.Add(VehicleTd);
                    HtmlTableCell CircsTd = new HtmlTableCell();

                    ParkLogDataContext pldc = new ParkLogDataContext();
                    List<CarInspect> inspects = pldc.CarInspect.Where(o => o.CID.Value == info.OrderId && o.Capability.Value == 2).OrderBy(o => o.Amount).ToList();
                    for (int n = 0; n < inspects.Count; n++)
                    {
                        string inspectName = "";
                        if (inspects[n].Amount.Value > 0)
                        {
                            inspectName = Device.GetDevice(inspects[n].EID.Value).DeviceName + "(数量：" + inspects[n].Amount + ")";
                        }
                        else
                        {
                            inspectName = pldc.Equipment.Where(o => o.ID == inspects[n].EID.Value).FirstOrDefault().ItemName;
                        }
                        CircsTd.InnerHtml += inspectName + "&nbsp;&nbsp;&nbsp;&nbsp;" + inspects[n].Remark + "<br/>";
                        //packLogs

                    }

                    SignContent content = new SignContent();
                    content.DepartmentId = DepartmentIds[i];
                    content.Oid = logs[j].OrderId;
                    content.Pid = logs[j].LogId;
                    content.Vid = logs[j].CarId;
                    content.Remark = CircsTd.InnerHtml;
                    packLogs.Add(content);

                    CircsTd.Attributes.Add("style", "border-color:#888888;border-collapse:  collapse; border-width: 1px; border-style:solid;text-align: left;");
                    tr.Cells.Add(CircsTd);
                    table.Rows.Add(tr);
                }
                Departtd.RowSpan = logs.Count;
            }
            #region 是否签字
            //caption
            //int NowWeek = GetWeekOfYear(DateTime.Now);
            ////是否是签字时间
            //if (NowWeek == (Convert.ToInt32(ddlWeek.SelectedValue) + 1))
            //{

            //    btnCaption.Visible = true;
            //    btnCaption0.Visible = true;
            //}
            //else
            //{
            //    btnCaption.Visible = false;
            //    btnCaption0.Visible = false;
            //}

            btnCaption.Visible = true;
            btnCaption0.Visible = true;


            lblCaption.Text = "";
            lblCaption0.Text = "";
            #endregion
            //打印按钮不显示
            btnPrint.Visible = false;
        }

        ViewState["packLogs"] = packLogs;

    }

    List<PackLogInfo> getPackLogInfos(string DepartmentId, DateTime startDate, DateTime endDate)
    {
        List<PackLogInfo> list = new List<PackLogInfo>();
        DataTable dt = Park.GetDamagePackLogInfo(DepartmentId, startDate, endDate);
        if (dt != null)
        {
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(new PackLogInfo() { CarId = new Guid(dr["CarId"].ToString()), LogId = new Guid(dr["LogId"].ToString()), OrderId = new Guid(dr["OrderId"].ToString()) });
            }
        }

        return list;

    }
    [Serializable]
    public class PackLogInfo
    {
        public Guid LogId;
        public Guid OrderId;
        public Guid CarId;
    }
    [Serializable]
    public class SignContent
    {
        public string DepartmentId;
        public Guid Oid;
        public Guid Pid;
        public Guid Vid;
        public string Remark;
        public Guid Sid;
    }
    //签字
    protected void Button1_Click(object sender, EventArgs e)
    {
        //部门ID
        string DepartmentId = "";
        if (Request["DepartmentId"] != null)
        {
            DepartmentId = Request["DepartmentId"];
        }
        else
        {
            DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        }
        DepartmentId = DepartmentId.Substring(0, 4) + "000";

        //开始时间和结束时间
        int year = Convert.ToInt32(ddlYear.SelectedValue);
        int week = Convert.ToInt32(ddlWeek.SelectedValue);
        DateTime YearOfOne = new DateTime(year, 1, 1);
        int dayofWeek = Convert.ToInt32(YearOfOne.DayOfWeek);
        if (dayofWeek == 0)
        {
            dayofWeek = 7;
        }
        DateTime StartTime = YearOfOne.AddDays((week - 1) * 7).AddDays(-dayofWeek + 1);
        DateTime EndTime = StartTime.AddDays(7);


        ParkLogDataContext pdc = new ParkLogDataContext();
        PackLogSign sign = pdc.PackLogSign.Where(o => o.DepartmentId == DepartmentId && o.WeekCout == week).FirstOrDefault();

        if (sign != null)
        {//已签字
            sign.Caption = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName;
            sign.DateCaption = DateTime.Now.Date;
            pdc.SubmitChanges();
        }
        else
        {
            sign = new PackLogSign();


            sign.Caption = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName;
            sign.DateCaption = DateTime.Now.Date;
            sign.DepartmentId = DepartmentId;
            sign.EndDate = EndTime;
            sign.Id = Guid.NewGuid();
            sign.StartDate = StartTime;
            sign.WeekCout = Convert.ToInt32(ddlWeek.SelectedValue);
            sign.year = Convert.ToInt32(ddlYear.SelectedValue);



            List<SignContent> SignContent = ViewState["packLogs"] as List<SignContent>;
            List<PackSignContent> packLogs = new List<PackSignContent>();
            if (SignContent.Count > 0)
            {
                sign.Flag = 1;
                foreach (SignContent content in SignContent)
                {
                    packLogs.Add(new PackSignContent()
                    {
                        Sid = sign.Id,
                        DepartmentId = content.DepartmentId,
                        id = Guid.NewGuid(),
                        Oid = content.Oid,
                        Pid = content.Pid,
                        Remark = content.Remark,
                        Vid = content.Vid
                    });
                }
            }
            else
            {
                sign.Flag = 0;
            }


            pdc.PackLogSign.InsertOnSubmit(sign);
            pdc.SubmitChanges();
            pdc.PackSignContent.InsertAllOnSubmit(packLogs);
            pdc.SubmitChanges();

        }
        BindData(DepartmentId);
    }
    protected void btnCaption0_Click(object sender, EventArgs e)
    {
        //部门ID
        string DepartmentId = "";
        if (Request["DepartmentId"] != null)
        {
            DepartmentId = Request["DepartmentId"];
        }
        else
        {
            DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        }
        DepartmentId = DepartmentId.Substring(0, 4) + "000";

        //开始时间和结束时间
        int year = Convert.ToInt32(ddlYear.SelectedValue);
        int week = Convert.ToInt32(ddlWeek.SelectedValue);
        DateTime YearOfOne = new DateTime(year, 1, 1);
        int dayofWeek = Convert.ToInt32(YearOfOne.DayOfWeek);
        if (dayofWeek == 0)
        {
            dayofWeek = 7;
        }
        DateTime StartTime = YearOfOne.AddDays((week - 1) * 7).AddDays(-dayofWeek + 1);
        DateTime EndTime = StartTime.AddDays(7);


        ParkLogDataContext pdc = new ParkLogDataContext();
        PackLogSign sign = pdc.PackLogSign.Where(o => o.DepartmentId == DepartmentId && o.WeekCout == week).FirstOrDefault();
        //中间部分
        if (sign != null)
        {//已签字
            sign.Caption0 = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName;
            sign.Caption0Date = DateTime.Now.Date;
            pdc.SubmitChanges();
        }
        else
        {
            sign = new PackLogSign();


            sign.Caption0 = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).UserName;
            sign.Caption0Date = DateTime.Now.Date;
            sign.DepartmentId = DepartmentId;
            sign.EndDate = EndTime;
            sign.Id = Guid.NewGuid();
            sign.StartDate = StartTime;
            sign.WeekCout = Convert.ToInt32(ddlWeek.SelectedValue);
            sign.year = Convert.ToInt32(ddlYear.SelectedValue);
            List<SignContent> SignContent = ViewState["packLogs"] as List<SignContent>;
            List<PackSignContent> packLogs = new List<PackSignContent>();
            if (SignContent.Count > 0)
            {
                sign.Flag = 1;
                foreach (SignContent content in SignContent)
                {
                    packLogs.Add(new PackSignContent()
                    {
                        Sid = sign.Id,
                        DepartmentId = content.DepartmentId,
                        id = Guid.NewGuid(),
                        Oid = content.Oid,
                        Pid = content.Pid,
                        Remark = content.Remark,
                        Vid = content.Vid
                    });
                }
            }
            else
            {
                sign.Flag = 0;
            }


            pdc.PackLogSign.InsertOnSubmit(sign);
            pdc.SubmitChanges();
            pdc.PackSignContent.InsertAllOnSubmit(packLogs);
            pdc.SubmitChanges();

        }
        BindData(DepartmentId);
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        ddlYear.SelectedValue = DateTime.Now.Year.ToString();
        ddlWeek.SelectedValue = Convert.ToString(GetWeekOfYear(DateTime.Now) - 1);
        BindWeekView();
        string DepartmentId = "";
        if (Request["DepartmentId"] != null)
        {
            DepartmentId = Request["DepartmentId"];
        }
        else
        {
            DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        }
        BindData(DepartmentId);
    }
    protected void LinkButton1_Click1(object sender, EventArgs e)
    {
        string DepartmentId = "";
        if (Request["DepartmentId"] != null)
        {
            DepartmentId = Request["DepartmentId"];
        }
        else
        {
            DepartmentId = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
        }
        BindData(DepartmentId);
        ExportData("application/ms-word", DateTime.Now.ToString("yyMdHm") + ".doc");
    }

    private void ExportData(string FileType, string FileName)
    {
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        dv.RenderControl(hw);
        Response.Write(tw.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);
    }
}
